import time

import requests
import schedule
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from datetime import datetime
from config import *

def check_mobil_data_balance_daily():
    print(f"{datetime.now()} - 开始执行流量检查任务...")
    # 创建 Edge 浏览器实例
    driver = webdriver.Edge()

    try:
        driver.get(router_ip)

        password_input = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.ID, "login_password"))
        )
        password_input.send_keys(router_pwd)

        WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.ID, "login_btn"))
        ).click()

        WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.ID, "first_menu_tools"))
        ).click()

        WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.ID, "left_menu_statistic"))
        ).click()


        remaining_value = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located(
                (By.XPATH, "//label[contains(text(), '剩余')]/following-sibling::label")
            )
        ).text

        print("剩余流量:", remaining_value)

        # 2. 构造请求URL（替换 {context}）
        url = f"https://api.day.app/{bark_key}/流量卡剩余流量每日提醒/{remaining_value}?group=流量卡&automaticallyCopy=1"

        # 3. 发送GET请求
        try:
            requests.get(url)
            # response.raise_for_status()  # 检查请求是否成功
            # print("请求成功！服务器返回:", response.text)
        except requests.exceptions.RequestException as e:
            print("请求失败:", e)

    except Exception as e:
        print(f"执行失败：{e}")

    finally:
        driver.quit()  # 手动关闭浏览器
        print(f"{datetime.now()} - 任务执行完毕")

# 设置工作日上午9点执行
schedule.every().monday.at("09:00").do(check_mobil_data_balance_daily)
schedule.every().tuesday.at("09:00").do(check_mobil_data_balance_daily)
schedule.every().wednesday.at("09:00").do(check_mobil_data_balance_daily)
schedule.every().thursday.at("09:00").do(check_mobil_data_balance_daily)
schedule.every().friday.at("09:00").do(check_mobil_data_balance_daily)

print("定时任务已启动，等待执行...")

while True:
    schedule.run_pending()
    time.sleep(60)  # 每分钟检查一次